/**
 * Created by Administrator on 2017/7/10 0010.
 */

var wxtool = {};
var crypto = require('crypto');
var request = require('request');
var userDao = require('../../dao/userDao');

var weChatConf = {
    "appID": "wxd44830a7fce3040d",
    "appSecret": "138c0d76b3ae5b0929760a8336158c37",
    "token": "tokenturnplate2017"
};

wxtool.wxInit = function (req,res) {

    var signature = req.query.signature;
    var timestamp = req.query.timestamp;
    var nonce = req.query.nonce;
    var echostr = req.query.echostr;

    /*  加密/校验流程如下： */
    //1. 将token、timestamp、nonce三个参数进行字典序排序
    var array = new Array(weChatConf.token,timestamp,nonce);
    array.sort();
    var str = array.toString().replace(/,/g,"");

    //2. 将三个参数字符串拼接成一个字符串进行sha1加密
    var sha1Code = crypto.createHash("sha1");
    var code = sha1Code.update(str,'utf-8').digest("hex");

    //3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
    //console.log('--code:%s,sig:%s',code,signature);
    if(code===signature){
        res.send(echostr)
    }else{
        res.send("error");
    }
};

wxtool.wxCode = function (req,res) {
    //console.log("oauth - login",req.headers.referee);
    // 第一步：用户同意授权，获取code
    // 这是编码后的地址,重定向后会跳转到这个地址
    var redirect_uri = 'http://weblogin.178dn.net/wxOpenid';
    var scope = 'snsapi_base';   //只获取openid,不需要用户手动点击同意 ,snsapi_userinfo 获取用户信息需要用户同意
    var redUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+weChatConf.appID+'&redirect_uri='+redirect_uri+'&response_type=code&scope='+scope+'&state=STATE#wechat_redirect';
    //req.referee = req.headers.referee;
    //console.log('----redUrl:',redUrl);
    request.get({url:redUrl}, function (error, response, body) {
        if(response.statusCode == 200) {

            // 第三步：拉取用户信息(需scope为 snsapi_userinfo)
            //console.log('redURL body:',JSON.parse(body));
            var data = JSON.parse(body);
            var openid = data.openid;
            var referee = req.referee;
            userDao.getUserById(openid, referee,null, function (err, user) {
                if (err) {
                    res.send({code: 1, info: '获取信息失败,请重试!'})
                } else {
                    res.send({code: 0, user: user,openid:openid});
                }
            });
        }
    });
};

wxtool.wxOpenid = function (req,res) {
    var access_code = req.headers.access_code;
    var referee = req.headers.referee;
    var regChannel = req.headers.regchannel;
    //console.log("1.access code:%s ,refe:%s",access_code,referee);

    // 第二步：通过code换取网页授权access_token
    request.get(
        {
            url:'https://api.weixin.qq.com/sns/oauth2/access_token?appid='+weChatConf.appID+'&secret='+weChatConf.appSecret+'&code='+access_code+'&grant_type=authorization_code'
        },
        function(error, response, body){
            if(response.statusCode == 200){

                // 第三步：拉取用户信息(需scope为 snsapi_userinfo)
                //console.log("2.wxOpenid body: ",JSON.parse(body));
                var data = JSON.parse(body);
                var openid = data.openid;
                if(openid == referee){
                    referee = null;
                }
                if(openid){
                    userDao.getUserById(openid,referee,regChannel, function (err,user) {
                        //console.log('3.-oid:%s-err:%s--user:%s',openid,err,JSON.stringify(user));
                        if(err){
                            res.send({code:1});
                        }else {
                            res.send({code:0,user:user,openid:openid});
                            if(referee && referee != null){        //如果有推荐人,那么查看他的二级推荐人是否存在,在的话就插入
                                userDao.getUserById(referee,null,null, function (err,user) {
                                    //console.log('4.about ref2 err:%s,user%s',err,JSON.stringify(user));
                                    if(!err  && user){
                                        if(user.referee1){
                                            //console.log('about ref1->ref2 user:%s',user.referee1);
                                            userDao.updateUserRef2(openid,user.referee1);
                                        }
                                    }
                                });
                            }
                        }
                    });
                }else {
                    res.send({code:1});
                    return;
                }

            }else{
                res.send({code:1});
            }
        }
    );
};

module.exports = wxtool;